//
//  TGGroupListController.m
//  GroupBuy
//
//  Created by wwj on 15/11/2.
//  Copyright © 2015年 wwj. All rights reserved.
//

#import "TGGroupListController.h"
#import "TGDealCollectionViewCell.h"
#import "TGGroupDetailController.h"
#import "TGNavigationController.h"
#import "UIBarButtonItem+Extend.h"
#import "MJRefresh.h"
#import "TGHttpRequest.h"
#import "TGDealModel.h"
#import "TGDataTool.h"
#import "TGTopMenu.h"
#import "DPAPI.h"
#import "TGCover.h"


#define kItemW 250
#define kItemH 250
#define kDetailW 600
@interface TGGroupListController ()<DPRequestDelegate>
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (assign, nonatomic) int page;
@property (strong, nonatomic) TGCover *coverView;
@end


@implementation TGGroupListController

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (id)init{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(kItemW, kItemH); // 每一个网格的尺寸
    layout.minimumLineSpacing = 20; // 每一行之间的间距
    return [self initWithCollectionViewLayout:layout];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加搜索框
    [self addSearchBar];
    
    //添加菜单
    [self addLeftMenu];
    
    self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    self.collectionView.backgroundColor = kBgColor;
    
    kAddNotification(refreshData)
    
    //注册Cell
    [self.collectionView registerNib:[UINib nibWithNibName:@"TGDealCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"deal"];
    
    [self addRefresh];
    
}


#pragma -mark 添加搜索框
- (void)addSearchBar{
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 210, 35)];
    searchBar.placeholder = @"请输入商品名、地址等";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
}

#pragma -mark 添加菜单
- (void)addLeftMenu{
    TGTopMenu *topMenu = [TGTopMenu topMenu];
    topMenu.contentView = self.view;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:topMenu];
}


#pragma -mark 城市改变通知
- (void)dataChangeNotificationWithBlock:(void(^)())finishBlock{
    [TGHttpRequest getGroupListWithPage:_page success:^(NSArray *dataArray, id totalCount) {
        if (finishBlock) {
            finishBlock();
        }
        
        [self.dataArray addObjectsFromArray:dataArray];
        [self.collectionView reloadData];

        if (_page >= [totalCount intValue]) {
            [self.collectionView.mj_footer endRefreshing];
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            
        }
    } error:^(NSError *error) {
        if (finishBlock) {
            finishBlock();
        }
    }];
    
}

#pragma -mark 刷新数据
-(void)refreshData{
    [self dataChangeNotificationWithBlock:^{
        [_dataArray removeAllObjects];
        [self.collectionView.mj_header endRefreshing];
    }];
}

-(void)loadMorData{
    _page++;
    [self dataChangeNotificationWithBlock:^{
        [self.collectionView.mj_footer endRefreshing];
    }];
}

#pragma mark 在viewWillAppear和viewDidAppear中可以取得view最准确的宽高（width和height）
- (void)viewWillAppear:(BOOL)animated{
   [self changSize];
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
    [self changSize];
}

-(void)changSize{
    // 1.取出layout
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    
    // 2.计算间距
    CGFloat v = 20;
    CGFloat h = 0;
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft ||
        [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) { // 竖屏
        h = (self.view.frame.size.width - 3 * kItemW) / 4;
        
    } else {
        h = (self.view.frame.size.width - 2 * kItemW) / 3;
        
    }
    [UIView animateWithDuration:2.0 animations:^{
        layout.sectionInset = UIEdgeInsetsMake(v, h, v, h);
    }];
}


#pragma -mark UICollection 代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"deal";
    TGDealCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.model = _dataArray[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self showCoverViewWithModel:_dataArray[indexPath.row]];
}


-(void)showCoverViewWithModel:(TGDealModel *)model{
    if (_coverView == nil) {
        _coverView = [TGCover coverWithTarget:self action:@selector(hiddenCoverView)];
    }
    _coverView.frame = self.navigationController.view.bounds;
    _coverView.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        [_coverView restCover];
    }];
    [self.navigationController.view addSubview:_coverView];
    
    TGGroupDetailController *groupDetailVC = [[TGGroupDetailController alloc] init];
    groupDetailVC.hiddenBlock = ^{
        [self hiddenCoverView];
    };
    groupDetailVC.model = model;
    TGNavigationController *naviVC = [[TGNavigationController alloc] initWithRootViewController:groupDetailVC];
    
    naviVC.view.frame = CGRectMake(_coverView.frame.size.width, 0, kDetailW, _coverView.frame.size.height);
    naviVC.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin;
    
    groupDetailVC.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"btn_nav_close.png" highIcon:@"btn_nav_close_hl.png" target:self action:@selector(hiddenCoverView)];
    
    [self.navigationController.view addSubview:naviVC.view];
    [self.navigationController addChildViewController:naviVC];
    
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = naviVC.view.frame;
        frame.origin.x -= kDetailW;
        naviVC.view.frame = frame;
    }];
}

-(void)hiddenCoverView{
    UIViewController *lastVC = self.navigationController.childViewControllers.lastObject;
    [UIView animateWithDuration:0.3 animations:^{
        _coverView.alpha = 0;
        CGRect frame = lastVC.view.frame;
        frame.origin.x += kDetailW;
        lastVC.view.frame = frame;
    } completion:^(BOOL finished) {
        [_coverView removeFromSuperview];
        [lastVC.view removeFromSuperview];
        [lastVC removeFromParentViewController];
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma -mark 集成刷新控件
-(void)addRefresh{
    _page = 1;
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    
    // 设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%d", i]];
        if (image) {
            [idleImages addObject:image];
        }
        
    }
    [header setImages:idleImages forState:MJRefreshStateIdle];
    
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=3; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_loading_0%d", i]];
        if (image) {
            [refreshingImages addObject:image];
        }
    }
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
    
    // 设置正在刷新状态的动画图片
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.collectionView.mj_header = header;
    
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMorData)];
    
    // 设置刷新图片
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    footer.automaticallyRefresh = YES;
    self.collectionView.mj_footer = footer;
}



@end
